× Introduction Applying CSS CSS Syntax CSS Selectors Grouping Color Background CSS Fonts CSS Text CSS Links Gradients The Box Model Margin and Padding Border Outline Measurement Units Dimension CSS Quick Reference Examples Projects eBooks






CSS Syntax

In this tutorial you will learn how to define CSS rules in your stylesheet.

A CSS stylesheet consists of a set of rules that are interpreted by the web browser and then applied to the corresponding elements such as paragraphs, headings, etc. in the document. A style rule is made of three parts: selector, property and value.

Example: Try It

p {
color:green;
}

In the example above p is a selector, color is the CSS property, and the green is the values of the property. Each declaration consists of a property and a value separated by a colon (:) and ending with a semicolon (;) although this is optional for the last one., and the declaration groups are surrounded by curly braces {}.

  • Selector: A selector is an HTML tag at which a style will be applied. This could be any tag like <h1> or <table> etc.
  • Property: A property is a type of attribute of HTML tag like color, font-size, border etc.
  • Value: Values are assigned to properties. For example, color property can have the value either red or rgb(125,150,250) etc.

Comments

The main use of comments is to clarify the code to developers, including you in the future. They can also be used to improve readability by delimiting sections of the style sheet or providing meta data about the file, such as the author’s name.

Comments in CSS are created by using the C-style notation (/* */). Everything placed between /* and */ will be ignored by browsers, even if the delimiters span multiple lines.

Single Line comment: Try It

/* This is a CSS comment */
p {
color: red; /* This is a CSS comment */
}

Multi Line comment: Try It

/*
This
is
a
CSS
comment
*/
p {
color: red;
}

Whitespace

Whitespace refers to spaces, tabs, and new lines. You are free to format your style sheets however you like with whitespace to make them easier to read. One common formatting convention is to split declarations across multiple lines.

Example: Try It

p  {
color:    red;
}

Another popular convention is to keep a rule’s declarations in a single line and split the declarations into multiple lines only when they become too numerous.

Example: Try It

p { color: red; margin: 1px; background-color:yellow;}

The formatting you use is a matter of preference. Choose the one that makes sense to you and aim to keep it consistent.

Case Sensitivity in CSS

CSS property names and many values are not case-sensitive. Whereas, CSS selectors are usually case-sensitive, for instance, the class selector .maincontent is not the same as .mainContent. Therefore, to be on safer side, you should assume that all components of CSS rules are case-sensitive.